package cn.wolfcode.business.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wolfcode.business.domain.BpmnInfo;
import cn.wolfcode.business.domain.BusAppointment;
import cn.wolfcode.business.domain.CarPackageAudit;
import cn.wolfcode.business.mapper.BpmnInfoMapper;
import cn.wolfcode.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.business.vo.AuditInfoVO;
import cn.wolfcode.business.vo.AuditVO;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.exception.ServiceException;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.SecurityUtils;
import cn.wolfcode.system.service.ISysConfigService;
import cn.wolfcode.system.service.ISysRoleService;
import cn.wolfcode.system.service.ISysUserService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.mapper.BusServiceItemMapper;
import cn.wolfcode.business.domain.BusServiceItem;
import cn.wolfcode.business.service.IBusServiceItemService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 服务项Service业务层处理
 * 
 * @author dalang
 * @date 2023-10-29
 */
@Service
@Transactional
public class BusServiceItemServiceImpl implements IBusServiceItemService 
{
    @Autowired
    private BusServiceItemMapper busServiceItemMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    /**
     * 查询服务项
     * 
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public BusServiceItem selectBusServiceItemById(Long id)
    {
        return busServiceItemMapper.selectBusServiceItemById(id);
    }

    /**
     * 查询服务项列表
     * 
     * @param busServiceItem 服务项
     * @return 服务项
     */
    @Override
    public List<BusServiceItem> selectBusServiceItemList(BusServiceItem busServiceItem)
    {
        return busServiceItemMapper.selectBusServiceItemList(busServiceItem);
    }

    /**
     * 新增服务项
     * 
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int insertBusServiceItem(BusServiceItem busServiceItem)
    {
        if (busServiceItem==null) {
            throw new ServiceException("参数非法");
        }
        int ret = busServiceItem.getOriginalPrice().compareTo(busServiceItem.getDiscountPrice());
        if (ret<0) {
            throw new ServiceException("折扣价不能大于原价");
        }

        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())) {
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }else{
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        }

        busServiceItem.setCreateTime(DateUtils.getNowDate());
        BusServiceItem temp = new BusServiceItem();
        BeanUtils.copyProperties(busServiceItem,temp);
        return busServiceItemMapper.insertBusServiceItem(temp);
    }

    /**
     * 修改服务项
     * 
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int updateBusServiceItem(BusServiceItem busServiceItem)
    {
        if (busServiceItem==null) {
            throw new ServiceException("参数非法");
        }
        int ret = busServiceItem.getOriginalPrice().compareTo(busServiceItem.getDiscountPrice());
        if (ret<0) {
            throw new ServiceException("折扣价不能大于原价");
        }

        BusServiceItem item = busServiceItemMapper.selectBusServiceItemById(busServiceItem.getId());
        if (BusServiceItem.SALESTATUS_ON.equals(item.getSaleStatus()) ||
               BusServiceItem.AUDITSTATUS_AUDITING.equals(item.getAuditStatus())) {
            throw new ServiceException("审核中或已上架的服务不允许编辑");
        }

        if (!item.getCarPackage().equals(busServiceItem.getCarPackage())) {
            throw new ServiceException("套餐与单项禁止更改");
        }

        // 套餐订单编辑后审核状态变为初始化
        if (BusServiceItem.CARPACKAGE_YES.equals(item.getCarPackage())) {
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
//            carPackageAuditMapper.updateStatusByServiceItemId(item.getId(),CarPackageAudit.STATUS_IN_ROGRESS)

        }

        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    /**
     * 批量删除服务项
     * 
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemByIds(Long[] ids)
    {
        return busServiceItemMapper.deleteBusServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     * 
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemById(Long id)
    {
        return busServiceItemMapper.deleteBusServiceItemById(id);
    }

    /**
     * 上架服务项信息
     *
     * @param id 服务项主键
     * @return
     */
    @Override
    public int putOnItem(Long id) {
        if (id==null) {
            throw new ServiceException("非法参数");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if (busServiceItem==null) {
            throw new ServiceException("非法参数");
        }
        if (BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())) {
            throw new ServiceException("无法上架已上架的订单");
        }
//        if (!(BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())||
//                BusServiceItem.AUDITSTATUS_NO_REQUIRED.equals(busServiceItem.getAuditStatus()))) {
//            throw new ServiceException("该审核状态无法上架");
//        }
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())&&
                !BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())) {
            throw new ServiceException("套餐需要审核通过才能上架");
        }
        busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_ON);
        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    @Override
    public int PullOffItem(Long id) {
        if (id==null) {
            throw new ServiceException("非法参数");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if (busServiceItem==null) {
            throw new ServiceException("非法参数");
        }
        if (BusServiceItem.SALESTATUS_OFF.equals(busServiceItem.getSaleStatus())) {
            throw new ServiceException("无法下架未上架的订单");
        }

        busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_OFF);
        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    @Override
    public AuditInfoVO auditInfo(Long id) {
        BusServiceItem serviceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if (serviceItem==null) {
            throw new ServiceException("参数异常");
        }
        AuditInfoVO vo = new AuditInfoVO();
        vo.setServiceItem(serviceItem);

        List<SysUser> shopOwners = sysUserService.queryByRoleKey("shopOwner");
        vo.setShopOwners(shopOwners);

        List<SysUser> finances = sysUserService.queryByRoleKey("finance");
        vo.setFinances(finances);

        String priceLimit = sysConfigService.selectConfigByKey("discountPriceLimit");
        if (StringUtils.hasText(priceLimit)) {
            priceLimit = "3000";
        }
        vo.setDiscountPrice(new BigDecimal(priceLimit));

        return vo;
    }

    @Override
    public void startAudit(AuditVO vo) {
        if (vo==null) {
            throw new ServiceException("参数异常");
        }
        BusServiceItem serviceItem = busServiceItemMapper.selectBusServiceItemById(vo.getId());
        if (serviceItem==null) {
            throw new ServiceException("参数异常");
        }
        if (!BusServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            throw new ServiceException("必须是套餐才允许审核");
        }
        if (!(BusServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())|| BusServiceItem.AUDITSTATUS_REPLY.equals(serviceItem.getAuditStatus()))) {
            throw new ServiceException("必须是初始化或者审核拒绝状态才可以进行审核");
        }

        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(vo.getId());
        audit.setServiceItemName(serviceItem.getName());
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setCreatorId(SecurityUtils.getUserId().toString());
        audit.setInfo(vo.getInfo());
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        audit.setCreateTime(new Date());
        carPackageAuditMapper.insertCarPackageAudit(audit);

        BpmnInfo bpmnInfo = bpmnInfoMapper.selectLastByType(CarPackageAudit.FLOW_AUDIT_TYPE);

        String businessKey = audit.getId().toString();
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        HashMap<String, Object> map = new HashMap<>();

        if (vo.getShopOwnerId()==null) {
            throw new ServiceException("参数异常");
        }
        map.put("shopOwnerId",vo.getShopOwnerId());
        if (vo.getFinanceId()!=null) {
            map.put("financeId",vo.getShopOwnerId());
        }

        map.put("disCountPrice",serviceItem.getDiscountPrice().longValue());

        ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, map);

        audit.setInstanceId(instance.getId());
        carPackageAuditMapper.updateCarPackageAudit(audit);

        busServiceItemMapper.updateServiceItemStatus(vo.getId(),BusServiceItem.AUDITSTATUS_AUDITING);

//        //参数判断
//        BusServiceItem serviceItem = busServiceItemMapper.selectBusServiceItemById(vo.getId());
//        if(serviceItem == null){
//            throw new ServiceException("参数异常");
//        }
//
//        if(!BusServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
//            throw new ServiceException("必须是套餐才允许审核");
//        }
//        if(!(BusServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())
//                || BusServiceItem.AUDITSTATUS_REPLY.equals(serviceItem.getAuditStatus()))){
//            throw new ServiceException("必须是初始化或者审核拒绝状态才可以进行审核");
//        }
//        //审核信息保存
//        CarPackageAudit audit = new CarPackageAudit();
//
//        audit.setInfo(vo.getInfo());
//        audit.setServiceItemId(vo.getId());
//        audit.setServiceItemName(serviceItem.getName());
//        audit.setServiceItemInfo(serviceItem.getInfo());
//        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
//        audit.setCreatorId(SecurityUtils.getUserId().toString());
//        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
//        audit.setCreateTime(new Date());
//        carPackageAuditMapper.insertCarPackageAudit(audit);
//
//        BpmnInfo bpmnInfo = bpmnInfoMapper.selectLastByType(CarPackageAudit.FLOW_AUDIT_TYPE);
//        //流程启动---businesskey   map(审核流程涉及参数)
//
//        String businessKey = audit.getId().toString();
//        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
//        Map<String, Object> map = new HashMap<>();
//
//        //设置节点审核人:财务
//        if(vo.getFinanceId() != null){
//            map.put("financeId", vo.getFinanceId());
//        }
//        //设置节点审核人:店长
//        if(vo.getShopOwnerId() != null){
//            map.put("shopOwnerId", vo.getShopOwnerId());
//        }
//        // 流程图中不支持BigDecimal 校验, 转换long类型
//        map.put("disCountPrice", serviceItem.getDiscountPrice().longValue());
//
//        ProcessInstance instance = runtimeService
//                .startProcessInstanceByKey(processDefinitionKey, businessKey, map);
//
//        //audit.setInstanceId(instance.getProcessInstanceId());  //流程实例id
//        audit.setInstanceId(instance.getId());  //流程实例id
//        carPackageAuditMapper.updateCarPackageAudit(audit);
//
//        //套餐项状态--审核中
//        serviceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_AUDITING);
//        busServiceItemMapper.updateBusServiceItem(serviceItem);

    }
}
